package com.rockchips.android.leanbacklauncher.modle.db;

import android.content.SharedPreferences;
import android.util.Log;

import com.rockchips.android.leanbacklauncher.LauncherApplication;
import com.rockchips.android.leanbacklauncher.apps.LaunchPoint;
import com.rockchips.android.leanbacklauncher.bean.AppInfo;
import com.rockchips.android.leanbacklauncher.data.ConstData;

import org.xutils.db.sqlite.WhereBuilder;

import java.util.ArrayList;
import java.util.List;

import momo.cn.edu.fjnu.androidutils.utils.StorageUtils;

/**
 * Created by GaoFei on 2017/6/30.
 * App项的增删改查
 */

public class AppInfoService extends AppBeanService<AppInfo>{

    @Override
    public boolean isExist(AppInfo object) {
        return false;
    }

    public List<AppInfo> getAppInfosByType(int type){
        List<AppInfo> appInfos = new ArrayList<>();
        try{
            appInfos = LauncherApplication.mDBManager.selector(AppInfo.class).where("appType", "=", type).findAll();
        }catch (Exception e){
            e.printStackTrace();
        }
        return appInfos;
    }

    public void deleteByType(int type){
        try{
             LauncherApplication.mDBManager.delete(AppInfo.class, WhereBuilder.b("appType", "=", type));
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public void saveByLaunchPoints(List<LaunchPoint> launchPoints, int type){
        String firstBoot = StorageUtils.getDataFromSharedPreference(ConstData.SharedKey.FIRST_BOOT);
        if (type == 0 && (firstBoot == null || firstBoot.isEmpty() )) {
            for(int i=0;i<launchPoints.size();i++){
                Log.d("LLL","saveByLaunchPoints LaunchPoint ComponentName:"+ launchPoints.get(i).mComponentName);
                launchPoints.get(i).mLaunchColor= ConstData.APP_ITEM_BACK_COLORS[i%ConstData.APP_ITEM_BACK_COLORS.length];
            }
            StorageUtils.saveDataToSharedPreference(ConstData.SharedKey.FIRST_BOOT, "false");
        }
        if(launchPoints != null && launchPoints.size() > 0){
            List<AppInfo> saveAppInfos = new ArrayList<>(launchPoints.size());
            for(LaunchPoint itemLaunchPoint : launchPoints){
                if(itemLaunchPoint.isAddItem())
                    continue;
                AppInfo appInfo = new AppInfo();
                appInfo.setAppType(type);
                appInfo.setCompentName(itemLaunchPoint.getComponentName());
                appInfo.setPackageName(itemLaunchPoint.getPackageName());
                saveAppInfos.add(appInfo);
            }
            saveAll(saveAppInfos);
        }
    }
}
